import {
	encryptBase64,
	encryptWithAes,
	generateAesKey,
	decryptWithAes,
	decryptBase64
} from '@/util/crypto';
import { encrypt, decrypt } from '@/util/jsencrypt';
let requestBaseUrl = ''
if (process.env.NODE_ENV === 'development') {
	// 开发环境（运行）http://43.136.102.40/prod-api
	requestBaseUrl = 'http://43.136.102.40/prod-api'
} else {
	// 生产环境（发行）https://www.hulele.net/prod-api
	requestBaseUrl = 'https://www.hulele.net/prod-api'
}
sessionStorage.setItem('requestBaseUrl',requestBaseUrl)
const requestConfig = {
	baseUrl: requestBaseUrl,
	timeout: 5 * 1000,
	headers: {
		'Accept-Language': 'zh-CN'
	},
};

export function request({
	method,
	url,
	data,
	loading,
	isEncrypt,
	config
}) {
	const {
		    baseUrl = '',
			timeout = 0,
			headers = {}
	} = {
		...requestConfig,
		...config
	};

	// 是否开启loading动画
	loading && uni.showLoading({
		title: 'loading'
	})

	// 当开启参数加密
	if (isEncrypt && (method === 'post' || method === 'put')) {
		// 生成一个 AES 密钥
		const aesKey = generateAesKey();
		headers['encrypt-key'] = encrypt(encryptBase64(aesKey));
		data = typeof data === 'object' ? encryptWithAes(JSON.stringify(data), aesKey) :
			encryptWithAes(data, aesKey);
	}else{
		
		delete headers['encrypt-key']
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method,
			url: `${baseUrl}${url}`,
			data,
			header: {
				...headers,
				'content-type': 'application/json',
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
				'clientId':uni.getStorageSync('clientId')
			},
			timeout,
			success: (res) => {
				// 无权限或者令牌过期
				if(res.data.code === 401){
					uni.removeStorageSync('token')
					uni.removeStorageSync('clientId')
					uni.removeStorageSync('shopId')
					uni.reLaunch({
						url:'/pages/login/login'
					})
				}
				if (res.statusCode === 200) {
					resolve(res.data);
				} else {
					reject(new Error(res.statusCode));
				}
			},
			fail: (err) => {
				let errorMessage = '';
				if (err.errMsg.includes('timeout')) {
					errorMessage = '请求超时，请稍后重试！';
				} else if (err.errMsg.includes('abort')) {
					errorMessage = '请求数据错误，请重试！';
				} else {
					errorMessage = '网络请求错误，请检查网络连接！';
				}
				reject(new Error(errorMessage))
			},
			//请求结束之后，执行的回调函数（成功或失败都会执行）
			complete() {
				//隐藏loading
				uni.hideLoading()
			}
		});
	});
}